package com.yiqihui.my_shiro_jwt_redis.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.yiqihui.my_shiro_jwt_redis.util.RedisUtil;
import com.yiqihui.my_shiro_jwt_redis.util.Result;
import com.yiqihui.my_shiro_jwt_redis.util.TokenUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @program: my_shiro_jwt_redis
 * @description:
 * @author: @Dog_Elder
 * @create: 2020-11-09 17:39
 **/
@Controller
public class LoginController {

    @PostMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response) throws JsonProcessingException {
//        User user=new User();
//        user.setUsername(username);
//        user.setPassword(password);
        //去数据库拿密码验证用户名密码，这里直接验证
        if(username.equals("admin")){
            if (!password.equals("admin")){
                return new Result(400,"密码错误");
            }
        }else if (username.equals("user")){
            if (!password.equals("user")){
                return new Result(400,"密码错误");
            }
        }else{
            return new Result(400,"无此用户");
        }
        Long currentTimeMillis = System.currentTimeMillis();
        String token= TokenUtil.sign(username,currentTimeMillis);
        RedisUtil.set(username,currentTimeMillis,TokenUtil.REFRESH_EXPIRE_TIME);
        response.setHeader("Authorization", token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return  Result.success();
    };
}